//
//  XJHButton.swift
//  PublicPod
//
//  Created by 许俊华 on 2021/9/6.
//

import UIKit

let kDoubleClickInterval:TimeInterval = 1

public enum kButtonStyle {
    case kButtonImageLeft        //图片在左
    case kButtonImageRight        //图片在右
    case kButtonImageTop          //图片在上
    case kButtonImageBottom       //图片在下
}

public class XJHButton: UIButton {

    private struct AssociatedKeys {
        static var eventInterval = "eventInterval"
        static var eventUnavailable = "eventUnavailable"
    }

    /// 重复点击的时间 属性设置
    public var eventInterval: TimeInterval {
        get {
            if let interval = objc_getAssociatedObject(self, &AssociatedKeys.eventInterval) as? TimeInterval {
                return interval
            }
            return 0.5
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.eventInterval, newValue as TimeInterval, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    /// 按钮不可点 属性设置
    private var eventUnavailable : Bool {
        get {
            if let unavailable = objc_getAssociatedObject(self, &AssociatedKeys.eventUnavailable) as? Bool {
                return unavailable
            }
            return false
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKeys.eventUnavailable, newValue as Bool, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    /// 新建初始化方法,在这个方法中实现在运行时方法替换
    class func initializeMethod() {
        let selector = #selector(UIButton.sendAction(_:to:for:))
        let newSelector = #selector(new_sendAction(_:to:for:))
        
        let method: Method = class_getInstanceMethod(UIButton.self, selector)!
        let newMethod: Method = class_getInstanceMethod(UIButton.self, newSelector)!
        
        if class_addMethod(UIButton.self, selector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod)) {
            class_replaceMethod(UIButton.self, newSelector, method_getImplementation(method), method_getTypeEncoding(method))
        } else {
            method_exchangeImplementations(method, newMethod)
        }
    }

    /// 在这个方法中
    @objc private func new_sendAction(_ action: Selector, to target: Any?, for event: UIEvent?) {
        if eventUnavailable == false {
            eventUnavailable = true
            new_sendAction(action, to: target, for: event)
            // 延时
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + eventInterval, execute: {
                self.eventUnavailable = false
            })
        }
    }
    
    /////////////////////////////////////////////////////////////////////////////////
    // 选中时的背景色
    private var _selectBackgroudColor:UIColor?
    public var selectBackgroudColor:UIColor {
        get {
            return _selectBackgroudColor!
        }
        set {
            _selectBackgroudColor = newValue
            if self.isSelected {
                self.backgroundColor = _selectBackgroudColor!
            }
        }
    }
    
    // 未选中时的背景色
    private var _normalBackgroudColor:UIColor?
    public var normalBackgroudColor:UIColor {
        set {
            _normalBackgroudColor = newValue
            self.backgroundColor = _normalBackgroudColor
        }
        get {
            return _normalBackgroudColor!
        }
    }
    
    // 高亮时的背景色
    private var _hightlightBackgroundColor:UIColor?
    public var hightlightBackgroundColor:UIColor {
        set {
            _hightlightBackgroundColor = newValue
        }
        get {
            return _hightlightBackgroundColor!
        }
    }
    
    // 选中时的边框颜色
    private var _selectBorderColor:UIColor?
    public var selectBorderColor:UIColor {
        set {
            _selectBorderColor = newValue
            if self.isSelected {
                self.layer.borderColor = _selectBorderColor!.cgColor
            }
        }
        get {
            return _selectBorderColor!
        }
    }
    
    // 未选中时的边框颜色
    private var _normalBorderColor:UIColor?
    public var normalBorderColor:UIColor {
        set {
            _normalBorderColor = newValue
            self.layer.borderColor = _normalBorderColor!.cgColor
        }
        get {
            return _normalBorderColor!
        }
    }
    
    // 边框宽度
    private var _borderWidth:CGFloat?
    public var borderWidth:CGFloat {
        set {
            _borderWidth = newValue
            self.layer.borderWidth = _borderWidth!
        }
        get {
            return _borderWidth!
        }
    }
    
    // 圆角大小
    private var _cornerRadius:CGFloat?
    public var cornerRadius:CGFloat {
        set {
            _cornerRadius = newValue
            self.layer.cornerRadius = _cornerRadius!
            self.layer.masksToBounds = true
        }
        get {
            return _cornerRadius!
        }
    }
    
    // 选中时的标题颜色
    private var _selectTitleColor:UIColor?
    public var selectTitleColor:UIColor {
        set {
            _selectTitleColor = newValue
            self.setTitleColor(_selectTitleColor!, for: .selected)
        }
        get {
            return _selectTitleColor!
        }
    }
    
    // 未选中时的标题颜色
    private var _normalTitleColor:UIColor?
    public var normalTitleColor:UIColor {
        set {
            _normalTitleColor = newValue
            self.setTitleColor(_normalTitleColor, for: .normal)
        }
        get {
            return _normalTitleColor!
        }
    }
    
    // 选中时的字体
    private var _selectTitleFont:UIFont?
    public var selectTitleFont:UIFont {
        set {
            _selectTitleFont = newValue
            if self.isSelected {
                self.titleLabel?.font = _selectTitleFont!
            }
        }
        get {
            return _selectTitleFont!
        }
    }
    
    // 未选中时的字体
    private var _normalTitleFont:UIFont?
    public var normalTitleFont:UIFont {
        set {
            _normalTitleFont = newValue
            self.titleLabel?.font = _normalTitleFont!
        }
        get {
            return _normalTitleFont!
        }
    }
    
    // 选中时的标题
    private var _selectTitle:String?
    public var selectTitle:String {
        set {
            _selectTitle = newValue
            self.setTitle(_selectTitle!, for: .selected)
        }
        get {
            return _selectTitle!
        }
    }
    
    // 未选中时的标题
    private var _normalTitle:String?
    public var normalTitle:String {
        set {
            _normalTitle = newValue
            self.setTitle(_normalTitle!, for: .normal)
        }
        get {
            return _normalTitle!
        }
    }
    
    // 重写选中方法
    public override var isSelected: Bool {
        willSet {
            
            print("changing from \(isSelected) to \(newValue)")
        }

        didSet {
            print("changed from \(oldValue) to \(isSelected)")
            if isSelected {
                if _selectBackgroudColor != nil {
                    self.backgroundColor = _selectBackgroudColor
                }
                if _selectBorderColor != nil {
                    self.layer.borderColor = _selectBorderColor?.cgColor
                }
                if _selectTitleFont != nil {
                    self.titleLabel?.font = _selectTitleFont
                }
            } else {
                if _normalBackgroudColor != nil {
                    self.backgroundColor = _normalBackgroudColor
                }
                if _normalBorderColor != nil {
                    self.layer.borderColor = _normalBorderColor?.cgColor
                }
                if _normalTitleFont != nil {
                    self.titleLabel?.font = _normalTitleFont
                }
            }
        }
    }
    
    public override var isHighlighted: Bool {
        willSet {
            
        }
        
        didSet {
            if _hightlightBackgroundColor != nil {
                if isHighlighted {
                    self.backgroundColor = _hightlightBackgroundColor
                } else {
                    if self.isSelected {
                        self.backgroundColor = _selectBackgroudColor
                    } else {
                        self.backgroundColor = _normalBackgroudColor
                    }
                    
                }
            }
            
        }
    }
    
    /**
    图片的位置，上、下、左、右，默认是图片居左
    */
    public var buttonStyle:kButtonStyle = .kButtonImageLeft
    
    /**
    文字与图片之间的间距，默认是0
    */
    public var padding:CGFloat = 0
    
    /**
     图片距离上下的距离
     */
    public var space:CGFloat = 0
    
    
    // MARK:初始化
    public class func buttonWithType(buttonType:UIButton.ButtonType) -> XJHButton {
        let mBtn:XJHButton = XJHButton.init(type: buttonType)
        mBtn.eventInterval = kDoubleClickInterval
        mBtn.imageView?.contentMode = .scaleAspectFill
        mBtn.imageView?.clipsToBounds = true
        return mBtn
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        //文案的宽度
        let labelWidth:CGFloat = (self.titleLabel?.frame.size.width)!
        //文案的高度
        let labelHeight:CGFloat = (self.titleLabel?.frame.size.height)!
        //button的image
        let image:UIImage = self.currentImage ?? UIImage()
        
        
        switch self.buttonStyle {
        case .kButtonImageLeft:
            self.imageEdgeInsets = UIEdgeInsets.init(top: self.space, left: -self.padding / 2, bottom: self.space, right: self.padding / 2)
            self.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: self.padding / 2, bottom: 0, right: -self.padding / 2)
            break
        case .kButtonImageRight:
            let imageHeight = self.frame.size.height - (2 * self.space)
            var imageWith = image.size.width
            // 是否图片较大
            if imageHeight < image.size.height {
                imageWith = (imageHeight / image.size.height) * image.size.width
            }
            self.imageEdgeInsets = UIEdgeInsets.init(top: self.space, left: labelWidth + self.padding / 2, bottom: self.space, right: -labelWidth - (self.padding / 2))
            self.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: -imageWith - (self.padding / 2), bottom: 0, right: imageWith + (self.padding / 2))
            break
        case .kButtonImageTop:
            //设置后的image显示的高度
            var imageHeight = self.frame.size.height - (2 * self.space) - labelHeight - self.padding
            if imageHeight > image.size.height {
                imageHeight = image.size.height
            }
            self.imageEdgeInsets = UIEdgeInsets.init(top: self.space, left: (self.frame.size.width - imageHeight) / 2, bottom: self.space + labelHeight + self.padding, right: (self.frame.size.width - imageHeight) / 2)
            self.titleEdgeInsets = UIEdgeInsets.init(top: self.space + imageHeight + self.padding, left: -image.size.width, bottom: self.space, right: 0)
            break
        case .kButtonImageBottom:
            //设置后的image显示的高度
            var imageHeight = self.frame.size.height - (2 * self.space) - labelHeight - self.padding
            if imageHeight > image.size.height {
                imageHeight = image.size.height
            }
            self.imageEdgeInsets = UIEdgeInsets.init(top: self.space + labelHeight + self.padding, left: (self.frame.size.width - imageHeight), bottom: self.space, right: (self.frame.size.width - imageHeight) / 2)
            self.titleEdgeInsets = UIEdgeInsets.init(top: self.space, left: -image.size.width, bottom: self.padding + imageHeight + self.space, right: 0)
            break
        default: break
            
        }
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
